package org.common4j2ee.s2shs.service.user;

import java.util.List;

import org.common4j2ee.s2shs.dao.user.AuthorityDaoImpl;
import org.common4j2ee.s2shs.dao.utils.Page;
import org.common4j2ee.s2shs.dao.utils.PropertyFilter;
import org.common4j2ee.s2shs.entity.user.Authority;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


@Component
@Transactional
public class AuthorityManager {

	@Autowired
	private AuthorityDaoImpl authorityDao;
	
	private static Logger logger = LoggerFactory.getLogger(UserManager.class);
	
	public String getAuthrityTree(List<Long> checkedAuthIds) {
		List<Authority> allParent = authorityDao.getAllParent();
		if (allParent != null) {
			StringBuffer sb = new StringBuffer();
			sb.append("<ul id=\"authorityTree\" style=\"background-color: #EEF2FB;\">");
			for (Authority auth : allParent) {
				buildTree(auth, sb, checkedAuthIds,"1");
			}
			sb.append("</ul>");
			return sb.toString();
		}
		return null;
	}

	private void buildTree(Authority auth, StringBuffer sb,
			List<Long> checkedAuthIds,String level) {
		sb.append("<li><a href=\"?").append(level).append("\">");
		sb.append("<input type=\"checkbox\" name=\"checkedAuthIds\" value=\"")
				.append(auth.getId()).append("\" id=\"checkedAuthIds-")
				.append(auth.getId()).append("\"");
		if (checkedAuthIds.contains(auth.getId())) {
			sb.append("checked=\"checked\"");
		}
		sb.append("/><label for=\"checkedAuthIds-").append(auth.getId())
				.append("\" class=\"checkboxLabel\">")
				.append(auth.getMenuName()).append("</label></a>");
		List<Authority> childList = auth.getChildrens();
		if(childList!=null&&childList.size()>0){
			int i=0;
			sb.append("<ul style=\"background-color: #EEF2FB;\">");
			for(Authority child:childList){
				buildTree(child, sb, checkedAuthIds,level+"."+i++);
			}
			sb.append("</ul>");
		}
		sb.append("</li>");
	}
	
	public List<Authority> getAllAuthList() {
		return authorityDao.getAll();
	}

	@Transactional(readOnly = true)
	public Page<Authority> searchAuthority(final Page<Authority> page,
			final List<PropertyFilter> filters) {
		return authorityDao.findPage(page, filters);
	}
	

	public void saveAuthority(Authority entity) {
		entity.setEnabled(1);
		authorityDao.save(entity);
	}

	/**
	 * 删除用户,如果尝试删除超级管理员将抛出异常.
	 */
	public void deleteAuthority(Long id) {
		authorityDao.delete(id);
	}

	public Authority getAuthority(Long id) {

		
		return authorityDao.get(id);
	}
	
	@Transactional(readOnly = true)
	public boolean isRoleNameUnique(String ResourceName, String ResourceMenuName) {
		return authorityDao.isPropertyUnique("name", ResourceName, ResourceMenuName);
	}
	

}
